package com.tarena.lbs.basic.web.repository;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.basic.web.mapper.AdminMapper;
import com.tarena.lbs.pojo.basic.bo.AdminBO;
import com.tarena.lbs.pojo.basic.dos.AdminDO;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.basic.query.AdminQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Repository
public class AdminRepository {
    @Autowired
    private AdminMapper adminMapper;
    public AdminBO getUserByPhone(String phone) {
        log.info("入参phone:{}",phone);
        AdminDO adminDO = adminMapper.selectAdminByPhone(phone);
        log.info("出参adminDO:{}",adminDO);
        AdminBO adminBO = new AdminBO();
        if (adminDO != null) {
            BeanUtils.copyProperties(adminDO,adminBO);
        }
        return adminBO;
    }

    public AdminBO getAdminById(Integer userId) {
        //1. 利用id查询 adminDO
        AdminDO adminDO=adminMapper.selectAdminById(userId);
        //2. 转化返回 考虑空
        AdminBO adminBO=null;
        if (adminDO!=null){
            adminBO=new AdminBO();
            BeanUtils.copyProperties(adminDO,adminBO);
        }
        return adminBO;
    }

    public BasePageList<AdminBO> adminList(AdminQuery adminQuery) {
        //1.开启pageHelper 才能查询 total
        PageHelper.startPage(adminQuery.getPageNo(),adminQuery.getPageSize());
        //2.保证线程安全 startPage下一步是sql查询搜 pageHelper线程安全问题 博文
        List<AdminDO> adminDOS = adminMapper.selectAdminByPage(adminQuery);
        //3.数据转化封装成 bo list.stream.map|for
        PageInfo<AdminDO> pageInfo = new PageInfo<>(adminDOS);
        //在total不为空的时候 封装一个basePageList
        long total = pageInfo.getTotal();
        BasePageList<AdminBO> basePageList = null;
        if (total > 0){
            List<AdminDO> dos = pageInfo.getList();
            List<AdminBO> bos = dos.stream().map(adminDO -> {
                AdminBO bo = new AdminBO();
                BeanUtils.copyProperties(adminDO,bo);
                return bo;
            }).collect(Collectors.toList());
            basePageList = new BasePageList<>(bos,total);
        }
        return basePageList;
    }


    public long AdminCountByPhone(String accountPhone) {
        return adminMapper.selectAdminCountByPhone(accountPhone);
    }

    public void save(AdminBO param) {
        AdminDO adminDO=new AdminDO();
        BeanUtils.copyProperties(param,adminDO);
        adminMapper.insert(adminDO);
    }

}
